<template>
  <div class="form">
    <div class="title">
      编辑个人信息
    </div>
    <el-form
      size="large"
      ref="userInfoFormRef"
      :model="userInfoForm"
      :rules="rules"
      label-width="70px"
      label-position="left"
    >
      <el-form-item prop="name" label="昵称：">
        <el-input v-model="userInfoForm.name"/>
      </el-form-item>
      <el-form-item prop="email" label="邮箱：">
        <el-input v-model="userInfoForm.email"/>
      </el-form-item>
      <el-form-item label="签名">
        <el-input
          v-model="userInfoForm.signature"
          :rows="3"
          type="textarea"
          placeholder="写句签名吧"
          resize="none"
          maxlength="30"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="性别：">
        <el-select v-model="userInfoForm.sex">
          <el-option
            v-for="item in sexOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生日">
        <el-date-picker
          v-model="userInfoForm.birth"
          type="date"
          placeholder="Pick a day"
        />
      </el-form-item>
      <el-form-item label="电话：">
        <el-input v-model="userInfoForm.phone"/>
      </el-form-item>
      <el-form-item label="地址：">
        <el-input v-model="userInfoForm.address"/>
      </el-form-item>
      <el-form-item style="margin-top: 3rem;">
        <el-button color="#4dcdef" size="large" class="button" @click="submitForm(userInfoFormRef)">
          <span class="button_text">保存</span>
        </el-button>
        <el-button color="#e15958" size="large" class="button" @click="cancel">
          <span class="button_text">取消</span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="avatar">
    <div class="avater-box">
      <img :src="userInfoForm.photo ? userInfoForm.photo:photo_default" alt="" style="height: 100%; width: 100%;">
    </div>
    <ProfileEditPhoto @out-url="uploadPic"/>
  </div>
</template>

<script setup>
import { ElMessage, ElNotification } from 'element-plus';
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from '../stores';
import { updateUserInfo } from '../api/api'
import ProfileEditPhoto from '../components/ProfileEditPhoto.vue';
import { useDefaultPhoto } from '../stores/photo';

// 表单dom
const userInfoFormRef = ref()
// 用户信息表
const userInfoForm = ref({
  name: '',
  email: '',
  photo: '',
  signature: '',
  sex: '',
  birth: '',
  phone: '',
  address: ''
})
// 默认头像
const photo_default = ref(useDefaultPhoto().photoUrl)
// 性别选项表
const sexOptions = ref([{
  value: 'man',
  label: '男'
}, {
  value: 'woman',
  label: '女'
}])

// 从store初始化数据
const store = useStore()
const init = async() => {
  userInfoForm.value.name = store.name
  userInfoForm.value.email = store.email
  userInfoForm.value.photo = store.photo
  userInfoForm.value.signature = store.signature
  userInfoForm.value.sex = store.sex
  userInfoForm.value.birth = store.birth
  userInfoForm.value.phone = store.phone
  userInfoForm.value.address = store.address
}
init()

// 验证邮箱格式
const checkEmail = (rule, value, callback) => {
  setTimeout(() => {
    let reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/
    if(reg.test(value)) {
      callback()
    } else {
      callback(new Error('邮箱格式错误'))
    }
  }, 500);
}
// ruls
const rules = ref({
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 3, max: 20, message: '昵称长度在3到20个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { validator: checkEmail, trigger: 'blur' }
  ]
})
// submit
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // 更新服务器
      updateUserInfo(store.id, userInfoForm.value).then(response => {
        // 根据返回信息更新store
        store.initStore(response.data)
        store.$patch({ userToken: response.data.id + response.data.name })
        // 根据store更新localStorage
        // 必须这么写，不然发布服务器报错（JSON.stringify的循环引用错误，我也不知道为什么！！！）
        let storeData = store.getStore()
        let userState = JSON.stringify(storeData)
        localStorage.setItem("userState", userState)     
        // 转跳页面
        router.push({name: 'user'})
        ElNotification({
          title: '修改成功',
          message: '个人信息已更新',
          type: 'success'
        })
      }).catch(error => {
        console.log(error)
        ElNotification({
          title: '修改失败',
          message: error.message,
          type: 'error'
        })
      })
      return true
    } else {
      ElNotification({
        title: '修改失败',
        message: '请规范填写后重新提交',
        type: 'error'
      })
      return false
    }
  })
}
// 取消
const router = useRouter()
const cancel = async() => {
  router.push({name: 'user'})
  ElMessage('已取消')
}
// 修改头像
const uploadPic = (url) => {
  userInfoForm.value.photo = url
  ElNotification({
    title: '修改成功',
    message: '头像修改成功，记得保存哦',
    type: 'success'
  })
}
</script>

<style scoped>
.form {
  height: 100%;
  width: 60%;
}
.avatar {
  height: 100%;
  width: 40%;
  padding-left: 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.avater-box {
  width: 11rem;
  height: 11rem;
  margin-top: 5rem;
  box-shadow: var(--el-box-shadow-light);
}
.title {
  text-align: left;
  font-size: 1.5rem;
  line-height: 3rem;
  font-weight: 600;
  padding-bottom: 1rem;
  margin-bottom: 1rem;
}
.button {
  width: 40%;
  box-shadow: var(--el-box-shadow-light);
}
.button_text {
  font-size: .9rem;
  font-weight: 700;
  color: #fff;
}
</style>